<template>
	<view class="play-page">
		<view class="video-main" v-if="showVideo && !tcType">
			<video id="myVideo" :src="url" :enable-progress-gesture="false" 
				   controls poster="" x5-playsinline="" playsinline="" webkit-playsinline="" :initial-time="videotime" :autoplay="autoplay" @play="startGo" @pause="pause" @ended="end" @timeupdate="timeupdate" ></video>
			<view class="zhe"></view>
			<!-- <span class="iconfont iconfanhuijiantou" @tap="back"></span> -->
		</view>
		<view class="video-main" id="video-main" v-if="showVideo && tcType">
			
			<!-- <span class="iconfont iconfanhuijiantou" @tap="back"></span> -->
		</view>
		<view class="course-list">
			<view class="test-item" v-for="(item,index) in courseList1" v-if="!tcType">
				<span class="title" v-show="item.detailType == '1'">{{item.title}}</span>
				<span class="title" v-show="item.detailType == '2'">{{item.paperTitles}}</span>
				<!-- <span class="time">{{item.createDate}}</span> -->
				<span class="go go1" v-show="item.detailType == '1'" :class="[{'noClick':!item.studyFlag},item.addClass]" @tap="goPlay(item,index)">{{item.text}}</span>
				<span class="go go1" v-show="item.detailType == '2'" :class="[{'noClick':!item.studyFlag},item.addClass]" @tap="goTest(item,index)">测试</span>
			</view>
			<view class="tc-box" v-if="tcType" v-for="(item1,index1) in List" >
				<view class="tc-name">{{item1.name}}</view>
				<view class="test-item" v-for="(item,index) in item1.list" >
					<span class="title">{{item.title}}</span>
					<!-- <span class="time">{{item.createDate}}</span> -->
					<span class="go go1" :class="[{'noClick':!item.studyFlag},item.addClass]"  @tap="goPlay1(List[index1].list,index)" v-if="item.fileId">{{item.text}}</span>
				</view>
			</view>
			
		</view>
	</view>
</template>

<script>
	import Cookies from 'js-cookie'

	export default {
		components:{
			
		},
		data() {
			return {
				number:5,
				textarea:"",
				id1:'',
				id2:'',
				videotime:0,
				isactive:false,
				showVideo:false,
				tcType:false,
				autoplay:false,
				list:[
					
				],
				content:{},
				courseList:[],
				start:false,
				courseList1:[],
				activeIndex:0,
				shangchuan:true,
				type:'',
				url:'',
				videoCourseDetailId:'',
				zongTime:0,
				privateId:'',
				videoContext:{},
				courseId:'',
				target:'0',

				shou:true,
	            show:false,
	            tcplayer:{},
	            player:{},
	            List:[],
	            List1:[],
	            wet:{},
	            title:'',
	            shangchuan:true,
	            videoStart:false,
	            privateId:'',
	            courseHours:0,
	            activeIndex:0,
	            courseId:'',
	            firstFlag:false,
	            target:'0',
	            blur:false,
	            playing:false,
	            isHand:false,
	            platObj:{},
	            userCurrentTime:0,
	            videoContext:{},
	            len:0,
	            allList:[],
	            item:{},
				dragFlag:1,//是否禁止拖动，0不可拖动，1可以拖动
			}
		},
		onLoad(obj) {
			this.id1 = obj.id1;
			this.id2 = obj.id2;
			
		},
		onReady(){
			this.getData();
		},
		onNavigationBarButtonTap(e) {
			console.log(e)
			this.submit();

			// uni.showToast({
			// 	title: e.index === 0 ? "你点了分享按钮" : "你点了收藏按钮",
			// 	icon: "none"
			// })
		},
		onBackPress(e){
			// var pages = getCurrentPages();//当前页
			// var beforePage = pages[pages.length - 2];//上个页面

			// console.log(beforePage,9)
			// return true;
		},
		onUnload(){
			if(this.tcType && this.videoStart){
	        console.log(33333)
	        this.player.dispose();
	      }
		},
		methods: {
			playtc(fileID,psign,detailId,item) {
              
              // let dom = document.getElementById("tcplayer");
              // // let dom = this.$refs.tcplayer;
              // // console.log(dom);
              // while (dom.hasChildNodes()) {
              //   //当div下还存在子节点时 循环继续
              //   dom.removeChild(dom.firstChild);
              //   // this.player.destroy();
              // }
              // // console.log(JSON.stringify(this.playVideo));
              // let objectString = JSON.stringify(this.playVideo);
              // if (objectString != "{}") {
              //   this.tcplayer = new TcPlayer("tcplayer", {
              //     m3u8_sd: 'http://2157.liveplay.myqcloud.com/2157_358535asd.m3u8', //请替换成实际可用的播放地址
              //     m3u8_hd: 'http://2157.liveplay.myqcloud.com/2157_358535ahd.m3u8',
              //     // flv_sd: this.playVideo.flv_sd, //请替换成实际可用的播放地址
              //     // flv_hd: this.playVideo.flv_hd, //请替换成实际可用的播放地址
              //     autoplay: true, //iOS 下 safari 浏览器，以及大部分移动端浏览器是不开放视频自动播放这个能力的
              //     // poster: "http://www.test.com/myimage.jpg",
              //     flash: false,
              //     h5_flv: true,
              //     width:  "100%", //视频的显示宽度，请尽量使用视频分辨率宽度
              //     height: "100%", //视频的显示高度，请尽量使用视频分辨率高度
              //     live: false,
              //     volume: 0.5,
              //     clarity: "sd",
              //     wording: {
              //       2032: "请求视频失败，请检查网络",
              //       2048: "请求m3u8文件失败，可能是网络错误或者跨域问题"
              //     }
              //   });
              // }
              // 
              const video = document.createElement("video") 
              video.setAttribute("id", "myVideo")
              video.setAttribute('playsinline',"")
              video.setAttribute('webkit-playsinline',"")
              video.setAttribute('x5-playsinline',"")
              document.getElementById("video-main").appendChild(video)
              let that = this;
              this.player = TCPlayer('myVideo', {
                fileID: fileID, // 请传入需要播放的视频 filID（必须）
                appID: '1251479152', // 请传入点播账号的 appID（必须）
                psign:psign,
                playbackRates:[],
                plugins:{
                    // ContinuePlay: { // 开启续播功能
                    //   auto: true, //[可选] 是否在视频播放后自动续播
                    //   // text:'上次播放至 ', //[可选] 提示文案
                    //   // btnText: '恢复播放' //[可选] 按钮文案
                    // },
                    ProgressMarker: true, //[可选] 进度条标记


                  }

              });
             
             let userCurrentTime = 0;
                if(item.userCurrentTime<item.duration){
                  //that.player.currentTime(item.userCurrentTime);
                  userCurrentTime = item.userCurrentTime
                }
              setTimeout(()=>{
                this.videoCourseDetailId = detailId;
                this.videoStart = true;
                
                

                
                
                this.player.play();
              
                
                

                this.playing = true;
                this.isactive = true;
              },100)

              var setTimeFlag = 1; // 用于安卓监听timeupdate，currentTime只赋值一次
				var userAgent_m = navigator.userAgent;
				// if(userAgent_m.indexOf("iPhone") > -1 || userAgent_m.indexOf("iOS") > -1){
				// 	// ios
				//     this.player.on("canplay", function(){
				//     	that.player.currentTime(userCurrentTime);
				//        //this.player[0].currentTime = userCurrentTime;
				//     });
				// }else{
				 	
				// }

              this.player.on("canplay", function(){
              		// uni.showToast({
		              //   	title:item.userCurrentTime.toString()
		              //   })

				});
              this.player.on('error', function(error) {
                setTimeout(()=>{
                  that.getUrl(item);
                },1000)
                
              });

              this.player.on('timeupdate', function(data) {
              	
                if(that.isactive == true){
                	if(setTimeFlag == 1){
				 				
				 		setTimeFlag = 2;
				 		setTimeout(()=>{
				 			that.player.currentTime(parseInt(userCurrentTime));
				 		},300)
			        	
			        	
			        }
                  // if(uni.getStorageSync("seeType")=="no" && that.player.currentTime()>Number(uni.getStorageSync("time"))){   
                  //   that.player.pause();
                  //   if(!that.tan){
                  //     that.tan = true;
                  //     that.$confirm('试看时间已到, 请购买课程继续观看?', '提示', {
                  //       confirmButtonText: '确定',
                  //       showCancelButton:false,
                  //       showClose:false,
                  //       closeOnClickModal:false,
                  //       type: 'warning'
                  //     }).then(() => {
                  //       if((that.content.courseVipType=="2" || that.content.courseVipType=="1") && !that.vip){
                  //         that.$router.push("/main/vip");
                  //         return;
                  //       }
                  //       that.$router.push("/main/orderPage/"+that.$route.params.id);
                  //       return;
                  //     }).catch(() => {
                                
                  //     });
                  //   }
                  // }
                  //that.zongTime = Math.floor(that.player.currentTime()+that.player.remainingTime());
                  var num = that.player.currentTime();
                  var b = Math.floor(num);
                  var courseHours = b;
                  // if( that.courseHours==0 ){
                  //   var num = that.player.currentTime();
                  //   var b = Math.floor(num);
                  //   courseHours = b;
                  // }
                  // else{
                  //   var time = null;
                  //   var num = that.player.currentTime();
                  //   var b = Math.floor(num);
                  //   time = b;
                  //   if(time>=that.courseHours){
                  //     courseHours = time;
                  //   }
                  //   else{
                  //     courseHours = that.courseHours;
                  //   }
                  // }
                  if(that.shangchuan==true){
                    if(uni.getStorageSync("token")){
                      that.shangchuan = false;
                      if(that.start){
                          // if(courseHours%5==0){
                          //     that.addStudyCenter(courseHours,5);
                          // }
                          // else{
                          //     that.addStudyCenter(courseHours,courseHours%5);
                          // }
                          that.addStudyCenter(courseHours,5);
                          
                      }
                      else{
                          //that.addStudyCenter(courseHours,0);
                      }
                      setTimeout(()=>{
                          that.shangchuan = true;
                          that.start = true;
                      },5*1000)
                    }
                  }
                }

              });

              this.player.on('playing', function(data) {
                that.playing = true;

              });

              this.player.on('pause', function(data) {
                that.playing = false;

              });

              this.player.on('ended', function(data) {
                that.playing = false;
                var num = that.player.currentTime();
                var b = Math.floor(num);
                let c = (Math.floor(that.player.currentTime()))%5;
                that.addStudyCenter(b,c);
                that.shangchuan = false;
                if(that.activeIndex<(that.len-1)){
                    that.activeIndex = that.activeIndex+1;
                    if(that.allList[that.activeIndex].fileId){

                      that.List.forEach((item,i)=>{
                        item.list.forEach((item1,i1)=>{
                          if(that.allList[that.activeIndex].fileId==item1.fileId){
                            item1.studyFlag = true;
                            

                            that.goPlay1(item.list,i1);
                          }
                        })
                      })
                      
                      
                      //that.play(that.activeIndex);
                    }
                    else{
                      if(that.activeIndex<(that.len-1)){
                        that.activeIndex = that.activeIndex+1;
                        that.List.forEach((item,i)=>{
                          item.list.forEach((item1,i1)=>{
                            if(that.allList[that.activeIndex].fileId==item1.fileId){
                              item1.studyFlag = true;
                              
                              that.goPlay1(item.list,i1);
                            }
                          })
                        })
                        
                      }
                      
                    }
                }

              });

              

              $(".vjs-control-bar").append("<div class='zhe'></div>")
              
        },
			timeupdate(data){
				if(this.isactive){
					var courseHours = 0;
	                if( this.videotime==0 ){
	                  var num = data.detail.currentTime;
	                  var b = Math.floor(num);
	                  courseHours = b;
	                }
	                else{
	                  var time = null;
	                  var num = data.detail.currentTime;
	                  var b = Math.floor(num);
	                  time = b;
	                  if(time>=this.videotime){
	                    courseHours = time;
	                  }
	                  else{
	                    courseHours = this.videotime;
	                  }
	                }
					if(this.shangchuan==true){
	                  if(uni.getStorageSync("token")){
	                    this.shangchuan = false;
	                    this.addStudyCenter(courseHours,5);
	                    setTimeout(()=>{
	                        this.shangchuan = true;
	                    },5*1000)
	                  }
	                }
				}
			},
			addStudyCenter(a,b){
	          var that = this;
	          let url = "";
	          if(this.tcType){
	          	url = '/f/saveUserVideoRecord?courseId='+this.courseId+'&courseType='+this.type+'&currentTime='+a+'&detailId='+this.videoCourseDetailId+'&rootCourseId='+this.privateId+'&studyTime='+b+'&target='+this.target+"&detail1Id="+this.item.chexuetang.id+"&detail2Id="+this.item.id
	          }
	          else{
	          	url = '/f/saveUserVideoRecord?courseId='+this.courseId+'&courseType='+this.type+'&currentTime='+a+'&detailId='+this.videoCourseDetailId+'&rootCourseId='+this.privateId+'&studyTime='+b+'&target='+this.target
	          }
	          this.$http.post(url)
	          .then(function (response) {
	              
	          })
	          .catch(function (error) {
	            // handle error
	            console.log(error);
	          })
	        },
			startGo(data){
				setTimeout(()=>{
      				this.videoContext.seek(parseInt(this.userCurrentTime))
      			},200)
				//this.videotime = this.videotime;
				// if (this.dragFlag == 0) {
				// 	document.querySelector(".uni-video-progress-container").style.pointerEvents ="none";
				// }
			},
			pause(data){

			},
			end(data){
				// var num = data.detail.currentTime;
	   //          var b = Math.floor(num);
	   //          let c = (Math.floor(data.detail.currentTime))%5;
				// console.log(num,5656)
	   //          this.addStudyCenter(b,c);
	            this.shangchuan = false;
	            if(this.activeIndex<(this.courseList1.length-1)){
	                this.activeIndex = this.activeIndex+1;
	                this.courseList1[this.activeIndex].studyFlag = true;
	                this.play(this.activeIndex);
	            }
			},
			getUrl(item){
				this.item = item;
				console.log(item,111)
	          let that = this;
	          if(that.tcType && that.videoStart){
	            console.log('销毁')
	              that.player.dispose();
	              //
	              // const video = document.getElementById("tcplayer")
	              // document.getElementById("left").removeChild(video)
	          }
	          let obj = {
	            fileid:item.fileId,
	            licence_id:item.licenceId,
	            type:'2'
	          }
	          this.$http.post("/chexuetang/psign",obj)
	          .then(function (response) {
	           
	              setTimeout(()=>{
	                that.activeIndex = item.index;
	                
	                let platObj = {};
	                platObj.fileId = item.fileId;
	                platObj.psign = response.data;
	                platObj.detailId = item.detailId;
	                that.platObj = platObj;
	                that.playtc(item.fileId,response.data,item.detailId,item)
	              },100)
	              
	              
	          })
	          .catch(function (error) {
	                // handle error
	                console.log(error);
	          })
	        },
			getData(){
				let that = this;
	            this.$http.get("/f/course?id="+this.id1)
	            .then(function (response) {
	                let data = Object.assign(response.data.course,response.data.course.courseInfo,response.data);
	                that.privateId = data.privateId;
            		that.courseId = data.courseId;
            		that.type = data.courseType;
					that.dragFlag = data.dragFlag
            		if(data.courseType!="10"){
            			if(Number(data.presentPrice)==0){
			                that.target = "0";
			                data.isTree = true;
			            }
			            else{
			                that.target = "1";
			            }
				        that.content = data;
				        
				        var list = data.educationCourseDbDetailsList;
	            
			            var len1 = list.length;
			            let arr = [];
			            for(var i=0;i<len1;i++){
			                if(list[i].detailType=='1'){
			                    list[i].addClass = "";
			                    list[i].url = list[i].videoCover;
			                      //list[i].time = Math.ceil(Number(list[i].duration)/60)
			                    list[i] = Object.assign(list[i],list[i].educationVideo);
			                    arr.push(list[i])
			                }else if(list[i].detailType=='2'){
								list[i].addClass = "";
								// list[i].url = list[i].videoCover;
								arr.push(list[i])
							}
			              
			            }
			         

			            that.courseList = arr;
			            var len = that.courseList.length;
			              for(var i=0;i<len;i++){
			                if(that.id2==that.courseList[i].id){
			                  var a = i;
			                  that.activeIndex = a;
			                  setTimeout(()=>{    
			                    that.play(a);
			                  },100) 
			                }
			              }
            		}
            		else{
            			that.tcType = true;
			              let allList = [];
			              let arr = [];
			              let list = data.educationCourseThirdDetailsList;
			              let len = 0;
			              
			              list.forEach((item,i)=>{
			                let licenceId = item.educationThirdChexuetang.licenceId;
			                let child = item.educationThirdChexuetang.educationThirdChexuetangDetailsList;
			                let arr1 = [];
			                if(child && child.length!=0){
			                  child.forEach((item1,i1)=>{
			                    item1.title = item1.name;
			                    item1.addClass = "";
			                    item1.licenceId = licenceId;
			                    item1.detailId= item.id;
			                    item1.index = len;
			                    len++;
			                    arr1.push(item1);
			                    allList.push(item1);
			                  })
			                }
			                let obj = {};
			                obj.name = item.educationThirdChexuetang.name;
			                if(item.educationUserStudyLast && item.educationUserStudyLast.detail2Id && item.educationUserStudyLast.detail2Id!=""){
			                  obj.detailId = item.educationUserStudyLast.detail2Id;
			                }
			                obj.list = arr1;
			                obj.id = item.educationThirdChexuetang.id;
			                arr.push(obj);
			              })
			              that.len = len;
			              
			              
			           		

			              arr.forEach((item,i)=>{

			                item.list.forEach((item1,i1)=>{
			                	item1.text = "播放";
			                	if(item.id==that.id2 ){
			                		if(item1.fileId){
					                    //item1.studyFlag = true;
					                    
					                    if(item.detailId){
					                    	if(item.detailId==item1.id){
					                    		item1.addClass = "active-bofang"
						                      item1.text = "播放中";
						                      that.showVideo = true;
						                      setTimeout(()=>{
						                      	that.getUrl(item1);
						                      },100)
					                    	}
					                    	
					                    }
					                    else{
					                    	if(i1==1){
						                      item1.addClass = "active-bofang"
						                      item1.text = "播放中";
						                      that.showVideo = true;
						                      setTimeout(()=>{
						                      	that.getUrl(item1);
						                      },100)
						                      
						                    }
					                    }
					                    
					                   
					                  }
			                	}
			                  
			                })
			                
			              })
			              that.allList = allList;
			              console.log(arr,1111111111,len)
			              that.List = arr;
            		}
            		

	            })
	            .catch(function (error) {
	              console.log(error);
	            })
				
			},
			goPlay1(List,index){
	            console.log(List,2233)
	            this.List.forEach((item,i)=>{
	            	if(index!=i){
	            		item.list.forEach((item1,i1)=>{
	            			item1.addClass = "";
	            			item1.text = "播放";
	            		})
	            	}
	            })
	            List.forEach((item1,i)=>{
	                if(i==index){
	                	if(item1.studyFlag){
	                			item1.addClass = "active-bofang"
			                    item1.text = "播放中";
			                    if(this.type=="10"){
			                        console.log(888)
			                        this.getUrl(item1)
			                      
			                      
			                    }
			                    else{
			                      console.log(999)
			                      //this.play(i);
			                    }
	                	}
	                    
	                    
	                }
	                else{
	                	item1.text = "播放";
	                    if(!item1.studyFlag && this.type=="10" && i==index){
	                      // Notification.warning({
	                      //   title:'提示',
	                      //   message:"暂无视频"
	                      // });
	                    }
	                    item1.addClass = ""
	                }
	            })
	            
	        },
			goPlay(item,index){
	            this.courseList1.forEach((item1,i)=>{
	                if(i==index && item1.studyFlag){
	                    item1.addClass = "active-bofang"
	                    this.play(i);
	                    item1.text = '播放中'
	                }
	                else{
	                    item1.addClass = ""
	                    item1.text = '播放'
	                }
	            })
	            
	        },
			goTest(item,index){
				//跳转到测试页面
				console.log(item,111)
				console.log(index,222)
				uni.navigateTo({
					url:'/pages/course/test?id=' + item.paperIds
				})
			},
			play(index){
	          var len = this.courseList.length;

	          var List = this.courseList;
	          for(var i=0;i<len;i++){
	            if(index==i){
	              List[i].addClass="active-bofang";
	              
	              this.videoCourseDetailId = List[i].did;
	              // this.videoCourseDetailId = List[i].id;
	              List[i].text="播放中";
	              this.zongTime = List[i].videoTime;
	              	
	              	this.showVideo = true;
	              	this.videoContext = wx.createVideoContext("myVideo");

	              	this.videoContext.stop();
              		this.url = List[i].videoUrl;
              		let a = List[i].userCurrentTime;
              		this.userCurrentTime = a;
              		//this.videotime = parseInt(a);
					// console.log(this.url,222)
              		setTimeout(()=>{
              			
              			this.videoContext.play();
              			
              		},300)
	              this.isactive = true;
	            }
	            else{
	              List[i].addClass="";
	              List[i].text="播放";
	            }
	          }
	          this.courseList1 = List;
	        },
			submit(type){
				if(this.textarea==""){
					uni.showToast({
						title:'请输入评价内容',
						icon:'none'
					})
				}
				let that = this;
				this.$http.post("/f/addPingFen?rootCourseId="+this.id+"&score="+this.number+"&content="+this.textarea+"&courseType="+this.content.courseType+"&courseId="+this.content.id)
			      .then(function (response) {
			        uni.showToast({
						title:'已提交',
						icon:'success'
					})
					setTimeout(()=>{
						that.back();
					},500)
			      })
			      .catch(function (error) {
			        // handle error
			        console.log(error);
			      })
				
			},
			back(){
				uni.navigateBack({
				    delta: 1
				});
			},
			select(index){
				this.list.forEach((item,i)=>{
					if(i==index){
						if(item.addClass!=""){
							item.addClass = ""
						}
						else{
							item.addClass = "active"
						}
					}
				})
			}
		}
	}
</script>

<style lang="less">
	.play-page{
		width:100%;
		height:100%;
		position:relative;
		background:#f5f5f5;
		float:left;
		.course-list{
			width:100%;
			height:calc(100% - 400rpx);
			overflow: hidden;
			overflow-y: auto;
			.tc-name{
				width:100%;
				line-height:40rpx;
				padding:15rpx 20rpx;
				text-align:center;
				background:#1783dd;
				color:#fff;
				font-size:32rpx;
				margin-top:30rpx;
				box-sizing:border-box;
			}
			.test-item{
				width:100%;
				margin:0 auto;
				margin-top:20rpx;
				background:#fff;
				display:flex;
				flex-wrap:wrap;
				align-items:flex-start;
				position:relative;
				.go{
					width: 130rpx;
				    height: 50rpx;
				    line-height: 50rpx;
				    position: absolute;
				    border-radius: 30rpx;
				    text-align: center;
				    right: 30rpx;
				    top: 50%;
				    background:#1783dd;
				    color: #ffffff;
				    font-size: 26rpx;
				    
				    transform:translateY(-50%);
				}
				.active-bofang{
					background:#19bbaa;
				}
				.title{
					display:block;
					line-height:40rpx;
					width:calc(100% - 80rpx);
					margin:20rpx auto;
					box-sizing:border-box;
					padding:0 40rpx;
					padding-right:130rpx;
					border-left:8rpx solid #1783dd;
					color:#555555;
					font-size:32rpx;
					overflow: hidden;    
				    text-overflow:ellipsis; 
					white-space: nowrap;
				}
				.time{
					display:block;
					line-height:30rpx;
					width:calc(100% - 80rpx);
					margin:0 auto;
					margin-top:0rpx;
					box-sizing:border-box;
					color:#888888;
					font-size:28rpx;
					margin-bottom:10rpx;
				}
			}
		}
		.video-main{
			width:100%;
			height:400rpx;
			background:#000000;
			position:relative;
			.zhe{
				width:64%;
				height:44px;
				left:18%;
				bottom:0;
				z-index:999;
				position:absolute;
			}
			.iconfont{
				display:block;
				z-index:999;
				width:70rpx;
				height:70rpx;
				text-align:center;
				line-height:70rpx;
				border-radius:50%;
				background:rgba(0,0,0,0.6);
				color:#fff;
				position:absolute;
				top:30rpx;
				left:30rpx;
				font-size:40rpx;
			}
		}
		#myVideo,.course-img{
				width:100%;
				height:400rpx;
			}
	}
	
	.zhe1{
        position:absolute;
        width: calc(100% - 21rem);
        top:0;
        right:6rem;
        height:100%;
    }
</style>
